import axios from 'axios';
import { Toast} from 'vant';
import api from "@/api/index";
import {isPlainObject } from 'lodash';
import store from '../store/store';
const service = axios.create({
  baseURL: api.ASSET_SERVER_URL,
  timeout: 90000,
  withCredentials: true
});

const setDataOpenid=(data)=>{
  const userInfo = store.state.app.ZRSUserInfo;
  const openid = userInfo?userInfo.openid:null;
  if(openid && openid!='' && openid!='null' && openid!='undefined'){
    if(data && isPlainObject(data)){
      if(!data.openid){
        data.openid=openid;
      }
    }else{
      data={openid:openid}
    }
  }
  return data;
}

service.interceptors.request.use(
  config => {
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

service.interceptors.response.use(
  response => {
    if (response.status === 200) {
      return response.data;
    }else{
      return Promise.reject(response);
    }
  },
  error => {
    return Promise.reject(error);
  }
);

/**
 * post 方法封装
 * @param url
 * @param data
 * @returns {Promise}
 */
function post(url, data = {}, config = {}, isShowError = true) {
  return new Promise((resolve, reject) => {
    service.post(url, setDataOpenid(data), config).then(
      response => requestResolveHandler(response, resolve, isShowError),
      err => requestRejectHandlerBuilder(err, reject)
    );
  });
}
/**
 * get 方法封装
 * @param url
 * @param data
 * @returns {Promise}
 */
function get(url, data = {}, isShowError = true) {
  return new Promise((resolve, reject) => {
    service.get(url, { params: setDataOpenid(data) }).then(
      response => requestResolveHandler(response, resolve, isShowError),
      err => requestRejectHandlerBuilder(err, reject)
    );
  });
}


function requestResolveHandler(response, resolve, isShowError) {
  if (response.code == 1) {
    return resolve(response);
  }else if(response.code == -1){
    location.href=process.env.NODE_ENV === 'development' ? '/login' : '/weChatApp/login'
  }else{
    if (isShowError) {
      const errorMsg = response && response.msg ? response.msg : '出错了';
      Toast.fail(errorMsg);
    }
  }
  return resolve(response);
}


function requestRejectHandlerBuilder(err, reject) {
  Toast.fail('网络错误');
  return reject(err);
}
export default { post, get};

